/*
*  LLFileSerializer.cpp
*  
*
*  Created by Alexander Trutchenko on 11/02/12.
*  Copyright 2012 Free Team. All rights reserved.
*
*/

#include "lid_lib/src/file_managment/LLFileSerializer.h"

#include "lid_lib/src/file_managment/LLFileUtils.h"
#include "lid_lib/src/service/LLAssert.h"

namespace lidlib {

////////////////////////////////////////////////////////
//
/** LLFileSerializer
*  
*/
////////////////////////////////////////////////////////

LLFileSerializer::LLFileSerializer(const std::string& relativeFilePath, bool readMode, unsigned int version)
: LLArchive(readMode)
, _descriptor(NULL)
, _relativeFilePath(relativeFilePath)
, _version(version)
{
	_descriptor = createDescriptorPlatform(LLFileUtils::getWriteablePath() + _relativeFilePath,
										   _readMode ? kLLFileDescriptorMode_read : kLLFileDescriptorMode_rewrite);
	if (_descriptor != NULL)
	{
		if (!_descriptor->isValid())
		{
			delete _descriptor; 
			_descriptor = NULL;
		}
		else
		{
			if (_readMode)
			{
				unsigned int fileVersion = 0;
				if (!_descriptor->readBlock(&fileVersion, sizeof(unsigned int)) ||
					_version != fileVersion)
				{
					delete _descriptor; 
					_descriptor = NULL;
				}
			}
			else
			{
				if (!_descriptor->writeBlock(&_version, sizeof(unsigned int)))
				{
					delete _descriptor; 
					_descriptor = NULL;
				}
			}
		}
	}
}	

LLFileSerializer::~LLFileSerializer()
{
	delete _descriptor; _descriptor = NULL;
}

////////////////////////////////////////////////////////
// Main interface

bool LLFileSerializer::readBlock(void* data, unsigned long size) const
{
	if (!_readMode || _descriptor == NULL)
		return false;

	return _descriptor->readBlock(data, size);
}
bool LLFileSerializer::writeBlock(const void* data, unsigned long size) const
{
	if (_readMode || _descriptor == NULL)
		return false;

	return _descriptor->writeBlock(data, size);
}

} // namespace lidlib
